#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          phone_server
# Required-Start:    $local_fs $remote_fs $network $syslog $mysql $redis-server
# Required-Stop:     $local_fs $remote_fs $network $syslog $mysql $redis-server
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: service and resource phone_server
# Description:       phone_server that record phone number
### END INIT INFO
# Startup script for the phone server.
#
# chkconfig: 345 85 15
# description: phone server
# processname: phone_server.py

PHONE_PATH=/space1/phone
DESC="phone server daemon"
NAME=phone_server.py
DAEMON=$PHONE_PATH/phone_server.py
PIDFILE=/var/run/phone_server.pid

SCRIPTNAME=/etc/init.d/phone_server

set -e

. /lib/lsb/init-functions

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

phone_start() {
  #$DAEMON --daemon --backend=mysql --bind=0.0.0.0 --mysqlhost=127.0.0.1 || echo -n " already running"
  #cd /space1/phone; NODE_PATH=/usr/local/lib/node_modules /usr/local/bin/forever start phone_server.js
  cd /space1/phone; NODE_PATH=/usr/local/lib/node_modules /usr/local/bin/pm2 start phone_server.js --name phone
}

phone_stop() {
  #kill -QUIT `cat $PIDFILE` || echo -n " not running"
  cd /space1/phone; NODE_PATH=/usr/local/lib/node_modules /usr/local/bin/pm2 kill
}

phone_reload() {
  #kill -HUP `cat $PIDFILE` || echo -n " can't reload"
  phone_stop
  sleep 1
  phone_start
}

case "$1" in
  start)
        echo -n "Starting $DESC: $NAME"
        phone_start
        echo "."
        ;;
  stop)
        echo -n "Stopping $DESC: $NAME"
        phone_stop
        echo "."
        ;;
  reload)
        echo -n "Reloading $DESC configuration..."
        echo "reload not supported. restarting"
        phone_reload
  ;;
  restart)
        echo -n "Restarting $DESC: $NAME"
        phone_stop
        sleep 1
        phone_start
        echo "."
        ;;
  *)
         echo "Usage: $SCRIPTNAME {start|stop|restart|reload}" >&2
         exit 3
        ;;
esac
exit 0
